<template>
    <div>
        <uploadExcel :on-success="handleSuccess" :before-upload="beforeUpload"></uploadExcel>

    </div>
</template>

<script>
import { importEmployees } from '@/api/employees'
import { formatExcelDate } from '@/utils'

export default {
    data() {
        return {
        }
    },
    methods: {
        beforeUpload(file) {
            const isLt1M = file.size / 1024 / 1024 < 1

            if (isLt1M) {
                return true
            }

            this.$message({
                message: 'Please do not upload files larger than 1m in size.',
                type: 'warning'
            })
            return false
        },
        async handleSuccess({ results, header }) {
            console.log('header', header)
            console.log('results', results)
            try {
                const res = await importEmployees(this.transExcel(results))
                console.log(res);
                this.$message.success(res.message)
                this.$router.back()
            } catch (error) {
                this.$message.error(error.message)
            }

        },
        /**
     * results excel表格的内容
      // [
          {'姓名'：'小张'， '手机号': '13712345678'}
        , {.....}
        ]

      // 目标
      // [ {'username'：'小张'，'mobile': '13712345678'}, {.....} ]
     */
        transExcel(results) {
            const mapInfo = {
                '入职日期': 'timeOfEntry',
                '手机号': 'mobile',
                '姓名': 'username',
                '转正日期': 'correctionTime',
                '工号': 'workNumber',
                '部门': 'departmentName',
                '聘用形式': 'formOfEmployment'
            }
            return results.map(zhObj => {
                const enObj = {}
                //    （1） 找出所有的中文key
                const zhKeys = Object.keys(zhObj) // ['姓名', '手机号']
                zhKeys.forEach(zhKey => {
                    // console.log(zhKey);
                    //     (2)  得到对应的英文key
                    const enKey = mapInfo[zhKey]
                    if (enKey === 'timeOfEntry' || enKey === 'correctionTime') {
                        enObj[enKey] = formatExcelDate(zhObj[zhKey])
                    } else {

                        //     (3)  拼接一个新对象： 英文key:值
                        enObj[enKey] = zhObj[zhKey]
                    }
                })

                return enObj
            })
        }
    }
}
</script>

<style scoped lang='scss'></style>